package com.yunhe.openapi.util;

import com.yunhe.common.util.MD5Util;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.Assert;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 解签
 */
public class SignDecodeUtil {
    private static final String salt = "@yunhe";

    public static boolean decode(Map<String, String> params){
        String secretKey =  params.getOrDefault("secretKey", null);
        String signStr =  params.getOrDefault("sign", null);
        return decode(params, secretKey, signStr);
    }

    public static boolean decode(Map<String, String> params, String secretKey, String signStr){
        Assert.isTrue(StringUtils.isNotBlank(secretKey), "secretKey异常");
        Assert.isTrue(StringUtils.isNotBlank(signStr), "sign异常");

        //1：移除可能冲突的key
        params.remove("sign");
        params.remove("accessKey");
        params.remove("secretKey");

        // 2：参数排序
        String[] keys = params.keySet().toArray(new String[0]);
        Arrays.sort(keys);

        // 3：把所有参数名和参数值串在一起
        StringBuilder query = new StringBuilder();
        for (String key : keys) {
            String value = params.get(key);
            if(query.length() > 0){
                query.append("&");
            }
            query.append(key).append("=").append(value);
        }
        query.append("&secretKey=").append(secretKey);

        //4：md5加密
        //String sign = SecureUtil.md5(query.toString());
        String sign = MD5Util.encode(query.toString(), salt);
        return sign.equals(signStr);
    }

    public static void main(String[] args){
        Map<String, String> params = new HashMap(){{
            put("a", "a1");
            put("d", "d1");
            put("c", "c1");
        }};
        String accessKey = "accessKey";
        String secretKey = "secretKey";
        String sign = SignEncodeUtil.encode(params, accessKey, secretKey);
        System.out.println(sign);

        Object res = decode(params, secretKey, sign);
        System.out.println(res);
    }
}
